<template>
  <div class="project-overview">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>项目总览</h2>
      <p>当前用户：{{ userStore.userInfo.realName }} ({{ userStore.userRole }})</p>
    </div>

    <!-- 搜索和筛选区域 -->
    <el-card class="search-card">
      <div class="search-filters">
        <div class="search-group">
          <label>根据项目名称等进行搜索</label>
          <el-input
            v-model="searchForm.keyword"
            placeholder="搜索项目名称..."
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        
        <div class="search-group">
          <label>点击后，可以根据进度等进行筛选</label>
          <el-select
            v-model="searchForm.progressFilter"
            placeholder="全部进度"
            clearable
            @change="handleSearch"
          >
            <el-option label="0-25%" value="0-25" />
            <el-option label="26-50%" value="26-50" />
            <el-option label="51-75%" value="51-75" />
            <el-option label="76-100%" value="76-100" />
          </el-select>
        </div>
        
        <div class="search-group">
          <label>排序方式</label>
          <el-select
            v-model="searchForm.sortBy"
            placeholder="选择排序方式"
            @change="handleSearch"
          >
            <el-option label="按创建时间" value="createTime" />
            <el-option label="按项目名称" value="name" />
            <el-option label="按进度" value="progress" />
          </el-select>
        </div>
      </div>
    </el-card>

    <!-- 项目列表 -->
    <el-card class="project-table-card">
      <template #header>
        <div class="table-header">
          <span>项目列表</span>
                  <el-button
          v-if="userStore.hasPermission('edit_project')"
          type="primary"
          size="small"
          @click="showAddDialog"
        >
          新增项目
        </el-button>
        </div>
      </template>

      <el-table
        :data="filteredProjects"
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="projectName" label="项目名称" min-width="150">
          <template #default="{ row }">
            <el-link
              v-if="canViewProject(row)"
              type="primary"
              @click="viewProjectDetails(row.id)"
            >
              {{ row.projectName }}
            </el-link>
            <span v-else class="project-name-disabled">
              {{ row.projectName }}
            </span>
          </template>
        </el-table-column>
        
        <el-table-column prop="leaderName" label="项目负责人" width="120" />
        
        <el-table-column prop="progress" label="项目进度 (%)" width="150">
          <template #default="{ row }">
            <div class="progress-container">
              <el-progress
                :percentage="row.progress"
                :color="getProgressColor(row.progress)"
                :stroke-width="8"
                show-text
              />
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="gitUrl" label="Git 地址" min-width="200">
          <template #default="{ row }">
            <el-link
              v-if="row.gitUrl"
              :href="row.gitUrl"
              target="_blank"
              type="primary"
            >
              {{ row.gitUrl }}
            </el-link>
            <span v-else>-</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="canViewProject(row)"
              type="primary"
              size="small"
              @click="viewProjectDetails(row.id)"
            >
              查看详情
            </el-button>
                    <el-button
          v-if="userStore.hasPermission('edit_project') && canEditProject(row)"
          type="warning"
          size="small"
          @click="showEditDialog(row)"
        >
          编辑
        </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 项目对话框 -->
    <ProjectDialog
      v-model:visible="showProjectDialog"
      :project="currentProject"
      @success="handleProjectSuccess"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import ProjectDialog from '@/components/ProjectDialog.vue'

const router = useRouter()
const userStore = useUserStore()

// 搜索表单
const searchForm = reactive({
  keyword: '',
  progressFilter: '',
  sortBy: 'createTime'
})

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 加载状态
const loading = ref(false)

// 导入模拟数据
import { mockProjects } from '@/api/mockData'

// 项目数据（模拟数据，实际应该从API获取）
const projects = ref([...mockProjects])

// 过滤后的项目列表
const filteredProjects = computed(() => {
  let result = [...projects.value]
  
  // 关键词搜索
  if (searchForm.keyword) {
    const keyword = searchForm.keyword.toLowerCase()
    result = result.filter(project => 
      project.projectName.toLowerCase().includes(keyword) ||
      project.leaderName.toLowerCase().includes(keyword)
    )
  }
  
  // 进度筛选
  if (searchForm.progressFilter) {
    const [min, max] = searchForm.progressFilter.split('-').map(Number)
    result = result.filter(project => 
      project.progress >= min && project.progress <= max
    )
  }
  
  // 排序
  result.sort((a, b) => {
    switch (searchForm.sortBy) {
      case 'name':
        return a.projectName.localeCompare(b.projectName)
      case 'progress':
        return b.progress - a.progress
      case 'createTime':
      default:
        return new Date(b.createdAt) - new Date(a.createdAt)
    }
  })
  
  return result
})

// 检查是否可以查看项目
const canViewProject = (project) => {
  return userStore.isMinister || 
         userStore.userInfo.id === project.leaderId ||
         userStore.hasPermission('view_all_projects')
}

// 检查是否可以编辑项目
const canEditProject = (project) => {
  return userStore.isMinister || 
         userStore.userInfo.id === project.leaderId ||
         userStore.hasPermission('edit_project')
}

// 获取进度颜色
const getProgressColor = (progress) => {
  if (progress >= 80) return '#67c23a'
  if (progress >= 60) return '#e6a23c'
  if (progress >= 40) return '#f56c6c'
  return '#909399'
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 0: return 'info'
    case 1: return 'primary'
    case 2: return 'warning'
    case 3: return 'success'
    default: return 'info'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 0: return '未开始'
    case 1: return '进行中'
    case 2: return '已暂停'
    case 3: return '已完成'
    default: return '未知'
  }
}

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1
  // 这里可以调用API进行搜索
}

// 查看项目详情
const viewProjectDetails = (projectId) => {
  router.push(`/dashboard/project-details/${projectId}`)
}

// 项目对话框相关
const showProjectDialog = ref(false)
const currentProject = ref(null)
const isEditMode = ref(false)

// 显示新增项目对话框
const showAddDialog = () => {
  isEditMode.value = false
  currentProject.value = null
  showProjectDialog.value = true
}

// 显示编辑项目对话框
const showEditDialog = (project) => {
  isEditMode.value = true
  currentProject.value = { ...project }
  showProjectDialog.value = true
}

// 处理项目操作成功
const handleProjectSuccess = (projectData) => {
  if (isEditMode.value) {
    // 更新项目
    const index = projects.value.findIndex(p => p.id === projectData.id)
    if (index !== -1) {
      projects.value[index] = { ...projects.value[index], ...projectData }
    }
    ElMessage.success('项目更新成功')
  } else {
    // 新增项目
    projects.value.unshift({
      ...projectData,
      id: Date.now(), // 临时ID，实际应该从后端获取
      createTime: new Date().toISOString().split('T')[0]
    })
    pagination.total = projects.value.length
    ElMessage.success('项目创建成功')
  }
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  // 重新加载数据
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  // 重新加载数据
}

// 页面加载时获取数据
onMounted(() => {
  // 这里应该调用API获取项目列表
  pagination.total = projects.value.length
})
</script>

<style scoped>
.project-overview {
  padding: 0;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  color: #303133;
  margin-bottom: 8px;
}

.page-header p {
  color: #606266;
  font-size: 14px;
}

.search-card {
  margin-bottom: 20px;
}

.search-filters {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}

.search-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
  min-width: 200px;
}

.search-group label {
  font-size: 12px;
  color: #606266;
  font-weight: 500;
}

.project-table-card {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.project-name-disabled {
  color: #c0c4cc;
  cursor: not-allowed;
}

.progress-container {
  width: 100%;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-filters {
    flex-direction: column;
  }
  
  .search-group {
    min-width: 100%;
  }
}
</style>
